const express = require("express");
const router = express.Router();
const MenuModel = require("../../../models/Menu");
const middleware_auth = require("../../../middleware/auth");
const assert = require("http-assert");
const { resData } = require("../../../utils/format");
const middleware_permission = require("../../../middleware/permission");
module.exports = app => {
    /**
     * @apiGroup 管理端/菜单
     * @api {get} /admin/api/menu 获取普通结构的菜单
     */
    router.get("/normallyGet", async (req, res) => {
        let data = await MenuModel.find();
        res.send(resData(data));
    });
    /**
     * @apiGroup 管理端/菜单
     * @api {get} /admin/api/menu/permissionMenus 获取带权限的菜单
     */
    router.get("/permissionMenus", async (req, res) => {
        let data = req.session.permissionMenus;
        let deepData = JSON.parse(JSON.stringify(data));
        let parentList = deepData.filter(item => !item.parentId);
        let childList = deepData.filter(item => item.parentId);
        let translateDataToTree = (parents, children) => {
            parents.forEach(parentItem => {
                children.forEach((childItem, childIndex) => {
                    if (String(parentItem._id) == String(childItem.parentId)) {
                        let temp = JSON.parse(JSON.stringify(children));
                        temp.splice(childIndex, 1);
                        translateDataToTree([childItem], temp);
                        if (parentItem.children) {
                            parentItem.children.push(childItem);
                        } else {
                            parentItem.children = [childItem];
                        }
                    }
                });
            });
        };
        translateDataToTree(parentList, childList);
        data = parentList;
        res.send(resData(data));
    });
    app.use("/admin/api/menu", middleware_auth(), middleware_permission(), router);
};
